package com.deloitte.service.rest.jersy;

import java.io.File;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.xslf.util.PPTX2PNG;

import com.deloitte.service.DocumentsLoadScheduler;
import com.deloitte.util.StringUtilities;

@Path("uploadfile")
public class FileUploadController {
	
	private static String rootPath;
	private static String fileSeparator;
	private static String indexSeperator;
	private static Properties prop=new Properties();
	
	static
	{
		try
		{
			InputStream is= FileUploadController.class.getClassLoader().getResourceAsStream("file.properties");			
			prop.load(is);
			is.close();		
			rootPath = prop.getProperty("rootpath");
			fileSeparator = prop.getProperty("fileseparator");
			indexSeperator = prop.getProperty("indexseperator");
		}
		catch(Exception exc)
		{
			exc.printStackTrace();
		}
	}
	
	public static String getRootPath(){
		return rootPath;
	}
	
	public static String getFileSeparator(){
		return fileSeparator;
	}
	
	public static String getIndexSeperator(){
		return indexSeperator;
	}
	

	@POST
	public Response  loadFile(@Context HttpServletRequest request) throws URISyntaxException {
		String resultStatus="fail";
		String selectedCatalog = request.getParameter("catalog");
		System.out.println("catalog "+selectedCatalog);
		 if (ServletFileUpload.isMultipartContent(request) && !StringUtilities.isEmpty(selectedCatalog)) { 
			 
			 	File file = new File(rootPath);
				if(!file.exists()){
					file.mkdir();
				}
				
				file = new File(rootPath,selectedCatalog);
				if(!file.exists()){
					file.mkdir();
				}
				
			 FileItemFactory factory = new DiskFileItemFactory();
			 ServletFileUpload upload = new ServletFileUpload(factory);
			 List<FileItem> items=null;
			try {
				items = upload.parseRequest(request);
			} catch (FileUploadException e) {
				
				e.printStackTrace();
			}
			if(items!=null) {
			 Iterator<FileItem> iter = items.iterator();  
			 while (iter.hasNext()) {  
				 FileItem item = iter.next();				 
			     if(!item.isFormField() && item.getSize() > 0) {  
				    	 String fileName = item.getName();
				    	 try {
							item.write(new File(rootPath+fileSeparator+selectedCatalog,fileName));
							//handle ppt file
							/*if(fileName.endsWith(".pptx")){
								handlePPTFile((rootPath+fileSeparator+selectedCatalog+fileSeparator+fileName));
							}*/
						} catch (Exception e) {
							e.printStackTrace();
						}  
				         resultStatus="ok";
			     }			     
			 }  
			}			
		 }
		String requestedUrl = request.getHeader("referer");
		if(StringUtilities.isEmpty(requestedUrl)){
			requestedUrl = "/admin";
		}
		System.out.println(" requestedUrl "+requestedUrl);
		URI uri = new URI(requestedUrl); 
		/*Enumeration<String> enu = request.getHeaderNames();
		if(enu != null){
			while(enu.hasMoreElements()){
				String key = enu.nextElement();
				String value = request.getHeader(key);
				System.out.println(key +" : "+value);
			}
		}*/
		Response response = Response.seeOther(uri).build();
		request.setAttribute("resultStatus",resultStatus);
		DocumentsLoadScheduler.loadDocsCache = true;
		return response;
	}
	
	private String processFileName(String fileNameInput) {
		String fileNameOutput=null;
		fileNameOutput = fileNameInput.substring(fileNameInput.lastIndexOf("\\")+1,fileNameInput.length());
		return fileNameOutput;
	}
	
	private void handlePPTFile(String pptFilePath){
		if(pptFilePath.endsWith(".pptx")){
			String[] args =  {pptFilePath};
			try {
				PPTX2PNG.main(args);
				//Delete the pptx file
				File file = new File(pptFilePath);
				if(file.exists()){
					file.deleteOnExit();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}
